<?php

namespace App\Services\Permission;

use Auth;
use Spatie\Permission\Models\Permission;

/**
 * 初始化网站所有的权限，后台获取权限并存入数据库
 * @package App\Services
 */
class PermissionService
{
    public function generate()
    {
        $permissions = include config_path() . '/permissions.php';

        return $this->init($permissions);

    }

    /**
     * 仅仅写入2级到数据库
     * @param $permissions
     */
    public function init($permissions)
    {
        collect($permissions)->map(function ($permission) {
            Permission::updateOrCreate(
                [
                    'name' => $permission['name'],
                    'title' => $permission['title'],
                    'icon' => $permission['icon'],
                    'path' => $permission['path']
                ]
            );
            if (array_key_exists('children', $permission)) {
                collect($permission['children'])->map(function ($item) {
                    Permission::updateOrCreate(
                        [
                            'name' => $item['name'],
                            'title' => $item['title'],
                            'icon' => $item['icon'],
                            'path' => $item['path']
                        ]
                    );
                });
            }
        });
    }


    public function getPermissions()
    {
        $permissions = include config_path() . '/permissions.php';
        $tree = [];

        foreach ($permissions as $key => $permission) {
            $tree[$key]['name'] = $permission['name'];
            $tree[$key]['title'] = $permission['title'];
            $tree[$key]['icon'] = $permission['icon'];
            $tree[$key]['path'] = $permission['path'];
            if (array_key_exists('children', $permission)) {
                foreach ($permission['children'] as $k => $item) {
                    $tree[$key]['children'][$k]['name'] = $item['name'];
                    $tree[$key]['children'][$k]['title'] = $item['title'];
                    $tree[$key]['children'][$k]['icon'] = $item['icon'];
                    $tree[$key]['children'][$k]['path'] = $item['path'];
                }
            }
        }
        return $tree;

        return dump($tree);

    }


    public function access($name): bool
    {
        //如果ID为1，表示超级管理员，拥有所有权限
        if (Auth::id() == 1) {
            return true;
        }
        //当前管理员拥有权限的名称
        return Auth::user()->can($name);
    }
}
